import os
import json
from datetime import datetime
from pathlib import Path


class SimpleDiary:
    def __init__(self, diary_file="diary.json"):
        """初始化日记本"""
        self.diary_file = Path(diary_file)
        self.entries = []
        self.load_entries()

    def _load_entries(self):
        """从文件加载到已有日记"""
        try:
            if self.diary_file.exists():
                with open(self.diary_file, 'r', encoding='utf-8') as f:
                    self.entries = json.load(f)
        except (json.JSONDecodeError, IOError) as e:
            print(f"警告：加载日记文件失败 - {e}")
            self.entries = []
    def _save_entries(self):
        """保存日记到文件"""
        try:
            with open(self.diary_file, 'w', encoding='utf-8') as f:
                json.dump(self.entries, f , indent=2, ensure_ascii=False)
        except IOError as e:
            print(f"错误： 保存日记失败 - {e}")

    def add_entry(self, content):
        """添加新日记"""
        entry = {
            "timestamp": datetime.now().isoformat(),
            "content": content.strip()
            }
        self.entries.append(entry)
        self._save_entries()
        print("日记已保存！")


    def view_entries(self, num=None):
        """查看日记历史"""
        if not self.entries:
            print("还没有日记记录")
            return
        entries_to_show = self.entries[-num:] if num else self.entries
        print("\n=== 日记历史 ===")
        for i,entry in enumerate(entries_to_show, 1):
            dt = datetime.fromisoformat(entry["timestamp"])
            print(f"\n[{i}] {dt.strftime('%Y-%m-%d %H:%M:%S')}")
            print("-" * 30)
            print(entry["content"])
        print("=" * 30)
        print(f"共 {len(self.entries)} 篇日记")
    def  search_entries(self, keyword):
        """搜索日记内容"""
        results = [
            entry for entry in self.entries
            if keyword.lower() in entry["content"].lower()
        ]
        if not results:
            print(f"没有找到包含‘{keyword}'的日记")
            return
        print(f"\n找到 {len(results)} 篇相关日记：")
        self.view_entries([entry for entry in results])

    def clear_entries(self):
        """清空所有日记"""
        confirm = input("确定要清空所有日记吗？（y/n）:").lower()
        if confirm == 'y':
            self.entries = []
            self._save_entries()
            print("日记已清空")

    def run(self):
        """运行日记本程序"""
        while True:
            print("\n===== 简易日记本 =====")
            print("1. 写日记")
            print("2. 查看历史")
            print("3. 搜索日记")
            print("4. 清空日记")
            print("5. 退出")

            choice = input("请选择操作（1-5）：")
            if choice == "1":
                content = input("\n请输入日记内容（空行结束）：\n")
                while True:
                    line = input()
                    if not line:
                        break
                    content += "\n" + line
                    if content:
                        self.add_entry(content)
                    else:
                        print("内容不能为空")
            elif choice == "2":
                try:
                    num = int(input("查看最近多少篇日记？）（留空查看全部）： ") or 0)
                except ValueError:
                    num = None
                    self.view_entries(num)
            elif choice == "3":
                keyword = input("请输入搜索关键词： ")
                self.seaerch_entries(keyword)
            elif choice == "4":
                self.clear_entries()
            elif choice == "5":
                print("再见！")
                break
            else:
                print("无效输入，请重新选择")


if __name__ == "__main__":
    diary = SimpleDiary()
    diary.run()




